from django.shortcuts import render
from qiniu import Auth
from rest_framework.views import APIView
from rest_framework.response import Response
import json
from tools.myredis import mredis
from tools.BaiduTool import baidu
import logging
from rest_framework import status
from tools.myjwt import mjwt
from user.models import User, UserVerify
from user.serializer import UserSerializer, UserVerifySerializer
from tools.qiniu_tool import qiniu_token
logger = logging.getLogger(__name__)
# Create your views here.


# 七牛云获得token
class QuToken(APIView):
    def get(self,request):
        # 构建七牛token方法调用
        token = qiniu_token()
        return Response({"code": 200, 'data': token})   # 返回token


# 身份证识别
class IDCard(APIView):

    # 百度身份证识别
    def post(self,request):
        picurl = request.data.get('picurl')   # 获取返回的图片路径
        logger.info(f"接收到图片URL: {picurl}")
        
        if not picurl:
            return Response({
                'code': 400,
                'message': '图片URL不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证URL格式
        if not picurl.startswith('http'):
            logger.error(f"URL格式错误: {picurl}")
            return Response({
                'code': 400,
                'message': '图片URL格式错误，必须以http开头'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 添加定时任务
        mredis.rpush('idcardlist',picurl)
        logger.info(f"已添加图片到队列: {picurl}")

        return Response({
            'code': 200,
            'message': '验证任务已提交，正在处理中',
            'data': {
                'picurl': picurl
            }
        }, status=status.HTTP_200_OK)

        # # 记录完整的URL信息
        # logger.info(f"准备调用百度API，URL: {picurl}")
        # logger.info(f"URL长度: {len(picurl)}")
        # # 检查特殊字符
        # special_chars = [' ', '\n', '\r', '\t']
        # has_special_chars = any(c in picurl for c in special_chars)
        # logger.info(f"URL是否包含特殊字符: {'是' if has_special_chars else '否'}")
        #
        # # 调用百度识别接口
        # result = baidu.idcard(picurl)
        # logger.info(f"百度API识别结果: {result}")
        #
        # if result.get('success'):
        #     # 获取识别结果
        #     name = result.get('name', '')
        #     idcard = result.get('idcard', '')
        #
        #     return Response({
        #         'code': 200,
        #         'name': name,
        #         'idcard': idcard
        #     })
        # else:
        #     logger.error(f"百度API识别失败: {result.get('message', '未知错误')}")
        #     return Response({
        #         'code': 400,
        #         'message': result.get('message', '识别失败')
        #     }, status=status.HTTP_400_BAD_REQUEST)


class Submit(APIView):  # 提交认证信息写入数据库 修改主表中的认证状态
    def post(self,request):
        # 记录完整的请求数据
        logger.info(f"收到提交请求，完整数据: {request.data}")
        logger.info(f"请求数据类型: {type(request.data)}")
        logger.info(f"请求数据键: {list(request.data.keys()) if hasattr(request.data, 'keys') else 'No keys'}")
        
        name = request.data.get('name')
        idcard = request.data.get('idcard')  # 修改为接收idcard
        image_url = request.data.get('image_url')
        userid = request.data.get('userid')
        
        logger.info(f"提交认证数据: name={name}, idcard={idcard}, userid={userid}, image_url={image_url}")
        logger.info(f"name类型: {type(name)}, idcard类型: {type(idcard)}, userid类型: {type(userid)}")
        
        if not all([name, idcard, userid]):
            logger.error(f"参数不完整: name={name}, idcard={idcard}, userid={userid}")
            return Response({
                'success': False,
                'message': '参数不完整'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 获取用户
            # 确保userid是整数
            try:
                userid_int = int(userid)
            except (ValueError, TypeError):
                logger.error(f"用户ID格式错误: {userid}")
                return Response({
                    'success': False,
                    'message': '用户ID格式错误'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            user = User.objects.get(id=userid_int)
            
            # 检查是否已经认证
            if user.get_verify_status() == "1":
                return Response({
                    'success': True,
                    'message': '已完成认证，无需再次认证'
                }, status=status.HTTP_200_OK)
            
            # 检查是否已经存在认证记录
            verify_record, created = UserVerify.objects.get_or_create(
                user=user,
                defaults={
                    'name': name,
                    'id_card': idcard,
                    'image_url': image_url  # 直接保存完整的图片URL
                }
            )

            if not created:
                # 如果已存在，更新信息
                verify_record.name = name
                verify_record.id_card = idcard
                verify_record.image_url = image_url
                verify_record.save()

            # 更新用户认证状态
            try:
                user.verify = '1'
                user.save()
            except:
                # 如果verify字段不存在，跳过更新
                logger.warning(f"用户 {user.username} 的verify字段不存在，跳过更新")

            logger.info(f"用户 {user.username} 实名认证成功")

            return Response({
                'success': True,
                'message': '实名认证成功',
                'data': {
                    'name': name,
                    'idcard': idcard,
                    'verify_status': '1'
                }
            }, status=status.HTTP_200_OK)

        except User.DoesNotExist:
            logger.error(f"用户不存在: {userid}")
            return Response({
                'success': False,
                'message': '用户不存在'
            }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.error(f"保存认证信息失败: {e}")
            return Response({
                'success': False,
                'message': '保存认证信息失败，请重试'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 获取认证状态：回显在页面上(查询)
class VerifyStatus(APIView):
    def get(self, request):
        try:
            # 从JWT token中获取用户信息
            token = request.headers.get('Authorization', '').replace('Bearer ', '')
            logger.info(f"收到认证状态请求，token长度: {len(token) if token else 0}")
            
            if not token:
                logger.error("未提供认证token")
                return Response({
                    'success': False,
                    'message': '未提供认证token'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 解析JWT token获取用户ID
            payload = mjwt.decode(token)
            logger.info(f"JWT解析结果: {payload}")
            
            if not payload:
                logger.error("JWT token解析失败")
                return Response({
                    'success': False,
                    'message': 'JWT token解析失败'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            user_id = payload.get('user_id')
            logger.info(f"从payload中获取的user_id: {user_id}")
            
            if not user_id:
                logger.error(f"token中未找到用户ID，payload内容: {payload}")
                return Response({
                    'success': False,
                    'message': 'token中未找到用户ID'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 获取用户信息
            user = User.objects.get(id=user_id)
            verify_status = user.get_verify_status()
            logger.info(f"成功获取用户信息: {user.username}, verify状态: {verify_status}")
            
            return Response({
                'success': True,
                'message': '获取认证状态成功',
                'data': {
                    'verify_status': verify_status,
                }
            }, status=status.HTTP_200_OK)
            
        except User.DoesNotExist:
            logger.error(f"用户不存在: user_id={user_id if 'user_id' in locals() else 'unknown'}")
            return Response({
                'success': False,
                'message': '用户不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logger.error(f"获取认证状态失败: {e}")
            return Response({
                'success': False,
                'message': '获取认证状态失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)




# 从Redis获取处理结果
class CheckIDCardmes(APIView):
    def get(self,request):
        picurl = request.GET.get('picurl')
        if not picurl:
            return Response({
                'code': 400,
                'message': '图片URL不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 从Redis获取处理结果
        data = mredis.get(picurl)
        if data:
            data = json.loads(data)
            return Response({
                'code': 200,
                'data': data
            }, status=status.HTTP_200_OK)
        else:
            # 检查是否还在队列中
            queue_length = mredis.llen('idcardlist')
            in_queue = False
            if queue_length > 0:
                items = mredis.lrange('idcardlist', 0, queue_length - 1)
                in_queue = any(
                    (item.decode('utf-8') if isinstance(item, bytes) else str(item)) == picurl 
                    for item in items
                )

            if in_queue:
                return Response({
                    'code': 202,
                    'message': '图片正在排队处理中'
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    'code': 202,
                    'message': '图片正在处理中...'
                }, status=status.HTTP_200_OK)